package com.mouliu.base.syn13;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author mouliu
 * @create 2018-04-07-上午11:43
 */
public class UseQueue {
    public static void main(String[] args) throws InterruptedException {
        //高性能无阻塞无界队列
//        ConcurrentLinkedQueue<String>q = new ConcurrentLinkedQueue<>();
//        q.offer("a");
//        q.offer("b");
//        q.offer("c");
//        q.offer("d");
//        q.add("e");
//
//
//        System.out.println(q.poll());
//        System.out.println(q.size());
//        System.out.println(q.peek());
//        //获取一个元素
//        System.out.println(q.size());
        //自定义5个元素的队列
/*        ArrayBlockingQueue<String> arr = new ArrayBlockingQueue(5);
        //如果队列满了，继续往里面加入数据offer方法会出现false
        arr.offer("a");
        arr.offer("b");
        arr.offer("c");
        arr.offer("d");
        arr.offer("e");
        arr.offer("f");
        System.out.println(arr.offer("k"));*/
//        System.out.println(arr.offer("a",3, TimeUnit.SECONDS));
        //阻塞队列
//        LinkedBlockingQueue<String>q =
//                new LinkedBlockingQueue<>();
//        q.offer("a");
//        q.offer("b");
//        q.offer("c");
//        q.offer("d");
//        q.offer("e");
//        q.add("f");
//        System.out.println(q.size());
//
//        for (Iterator iterator=q.iterator();iterator.hasNext();){
//            String string = (String) iterator.next();
//            System.out.println(string);
//        }
//        //把链表队列转换为List集合
//        List<String> list = new ArrayList<String>();
//        System.out.println(q.drainTo(list,3));
//        System.out.println(list.size());
//        for (String string:list){
//            System.out.println(string);
//        }
        final SynchronousQueue<String> q =
                new SynchronousQueue<>();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(q.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                q.add("asdasd");
            }
        });
        t2.start();
    }
}